<template>
  <div>
    <h2>添加商品</h2>
    标题<input type="text" v-model="title">
    价格<input type="number" v-model="price">
    图片<input type="file" id="img">
    分类<select v-model="cate">
      <option v-for="i in cates" :key="i.id" :value="i.id">{{i.name}}</option>
    </select>
    <button @click="sub">添加</button>
  </div>
</template>

<script>
export default {
  data(){
    return{
      title:'',
      price:0,
      cate:0,
      cates:[]
    }
  },
  mounted(){
    this.axios({
      url:'http://127.0.0.1:8000/cate/',
      method:'get'
    }).then(res=>{
      //
      this.cates=res.data;
    })
  },
  methods:{
    sub:function(){
      // 获取图片
      let img=document.getElementById('img').files[0]

      // 实例化formdata
      let formdata=new FormData();

      // 将数据添加到formdata
      formdata.append('title',this.title);
      formdata.append('price',this.price);
      formdata.append('cate',this.cate);
      formdata.append('img',img);

      // 向后端发送数据
      this.axios({
        url:'http://127.0.0.1:8000/good/',
        method:'post',
        data:formdata
      }).then(res=>{
        alert('成功');
      }),error=>{
        alert(error.responser.data);
      }

    }
  }
}
</script>

<style>

</style>
